package com.fdb.efp.nls.service.impl.yed.apply;

import com.fdb.efp.nls.service.facade.ed.LimitControlsService;
import com.fdb.efp.nls.service.vo.NlsApplyInfoVO;
import com.fdb.efp.nls.service.vo.queue.NlsProcessBizVO;
import com.fdb.basic.framework.core.constant.SDicToExternalConstant;
import com.fdb.basic.framework.core.exception.BizException;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.util.ValidationUtils;
import com.fdb.basic.framework.core.util.sdic.SDicToExternal;
import com.fdb.efp.nls.common.ConsoleConstant;
import com.fdb.efp.cus.service.facade.CusIndivRelService;
import com.fdb.efp.cus.service.vo.CusIndivRelVO;
import com.fdb.efp.esb.common.constant.InstitutionEnums;
import com.fdb.efp.esb.common.constant.MsLoanConstant;
import com.fdb.efp.esb.service.bo.req.yx.ApplyRiskInfArryBean;
import com.fdb.efp.esb.service.bo.req.yx.YedApplyRiskApproveReq;
import com.fdb.efp.esb.service.bo.resp.yx.YedApplyRiskApproveResp;
import com.fdb.efp.esb.service.facade.esb.EsbService;
import com.fdb.efp.limit.service.facade.LmtPrdContService;
import com.fdb.efp.limit.service.vo.LmtPrdContVO;
import com.fdb.efp.nls.service.facade.AccLoanService;
import com.fdb.efp.nls.service.vo.AccLoanVO;
import com.fdb.efp.nls.service.impl.SoltServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 优e贷风控审批通知接口插槽  网贷-》风控
 *
 * @author liangcongming :2020/7/31 8:46
 * @version 0.1
 * @date 2020/7/31 8:46
 * @since 2020/7/31 8:46
 */
@Service("yedApplyRiskApproveSoltService")
public class YedApplyRiskApproveSoltServiceImpl extends SoltServiceImpl {

    private static Logger log = LoggerFactory.getLogger(YedApplyRiskApproveSoltServiceImpl.class);

    @Autowired
    @Qualifier("limitControlsService")
    private LimitControlsService limitControlsService;

    @Autowired
    @Qualifier("accLoanService")
    private AccLoanService accLoanService;

    @Autowired
    @Qualifier("yedApplyRiskApproveService")
    private EsbService<YedApplyRiskApproveReq, YedApplyRiskApproveResp> yedapplyRiskApproveService;

    @Autowired
    @Qualifier("cusIndivRelService")
    private CusIndivRelService cusIndivRelService;

    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;

    @Override
    protected void doExecute(NlsProcessBizVO nlsProcessBizVo, NlsApplyInfoVO nlsApplyInfoVO) throws Exception {
        log.info("优e贷用信风控审批接口接口调用插槽开始执行,流水号："+nlsApplyInfoVO.getApplySeq());
        try {
            String certType = nlsApplyInfoVO.getCertType();
            String certCode = nlsApplyInfoVO.getCertCode();

            YedApplyRiskApproveReq applyRiskReq = YedApplyRiskApproveReq.builder().build();

            // 当前贷款逾期状态(网贷) 其中'0'代表无逾期,'1'代表有逾期
            AccLoanVO accLoanVO = accLoanService.queryOverdue(certType, certCode);

            //查询网贷占用额度
            BigDecimal preOccAmt = limitControlsService.getPreOccAmt2(certCode, certType, nlsApplyInfoVO.getApplyAmt());

            //查询客户最新的联系人信息，优e贷只有一个联系人
            CusIndivRelVO cusIndivRelVO = new CusIndivRelVO();
            cusIndivRelVO.setCusId(nlsApplyInfoVO.getCusId());
            List<CusIndivRelVO> cusIndivRelVOs = Optional.ofNullable(cusIndivRelService.queryByPkCusId(cusIndivRelVO)).orElseGet(ArrayList::new);
            if(cusIndivRelVOs == null || cusIndivRelVOs.isEmpty()){
                throw new BizException("联系人信息为空");
            }
            CusIndivRelVO qryCusIndivRelVO = cusIndivRelVOs.get(0);

            //查询额度有效期
            LmtPrdContVO lmtPrdContVO = new LmtPrdContVO();
            lmtPrdContVO.setLmtApplySeq(Objects.requireNonNull(nlsApplyInfoVO.getLmtApplySeq()));
            lmtPrdContVO = lmtPrdContService.queryByPk(lmtPrdContVO);

            //参数校验不通过直接抛异常
            validateParam(nlsApplyInfoVO,lmtPrdContVO,qryCusIndivRelVO,preOccAmt);

            String relation = "";
            try{
                relation = SDicToExternal.getExternalSysDicVal(SDicToExternalConstant.SYSID_RDP, SDicToExternalConstant.CONSTACTS_RELATION, qryCusIndivRelVO.getRelation());
            }catch (Exception e){
                relation = "00000";
            }

            ApplyRiskInfArryBean  applyRiskInfArryBean = ApplyRiskInfArryBean.builder()
                    .DeptNo(InstitutionEnums.InstitutionEnum.GZYHZHYHZX.getCode())
                    .CustNo(nlsApplyInfoVO.getCusId())
                    .AppNo(nlsApplyInfoVO.getApplySeq())
                    .MainCardAplcNm(nlsApplyInfoVO.getCusName())
                    .Age(String.valueOf(ValidationUtils.getAgeFromIdNumber(nlsApplyInfoVO.getCertCode())))
                    .AplcIdentNo(certCode)
                    .AplcIdentTp(certType)
                    .IdentVldty(nlsApplyInfoVO.getIndivIdExpDt())
                    .CtcTel(nlsApplyInfoVO.getMobile())
                    .CanLoanLmt(String.valueOf(lmtPrdContVO.getAvailAmt()))
                    .LmtVldty(Objects.isNull(lmtPrdContVO) ? "" : lmtPrdContVO.getExpireDate())
                    .AppAmt(String.valueOf(nlsApplyInfoVO.getApplyAmt()))
                    .AppLoanTrm(nlsApplyInfoVO.getLoanTerm())
                    .CrspTel(qryCusIndivRelVO.getMobile())
                    .CrspNm(qryCusIndivRelVO.getRelName())
                    .WthCrspRelaTp(relation)
                    .CrnLoanSt(Objects.isNull(accLoanVO) ? ConsoleConstant.NOT_OVERDUE :ConsoleConstant.OVERDUE)
                    .NetwrkLoanOcptnLmt(String.valueOf(preOccAmt))
                    .build();
            applyRiskReq.setApplyInfArry(Collections.singletonList(applyRiskInfArryBean));

            YedApplyRiskApproveResp service = yedapplyRiskApproveService.service(applyRiskReq);

            if(!MsLoanConstant.RetCodeEnum.SUCCESS.VALUE.equals(service.getApplyRiskInfArry().get(0).getRcvSt())){
                throw new BizException("用信风控接口调用失败，原因："+service.getApplyRiskInfArry().get(0).getRcvRsltInf());
            }

        } catch(BizException ne){
            log.error("优e贷用信风控审批接口必填项为空或数据异常",ne);
            nlsProcessBizVo.setExceptionFlag(true);
            nlsProcessBizVo.setExceptionMsg(ne);
        } catch (Exception e) {
            log.error("优e贷用信风控审批接口调用插槽执行异常",e);
            nlsProcessBizVo.setExceptionFlag(true);
            nlsProcessBizVo.setExceptionMsg(e);
        } finally {
            log.info("优e贷用信风控审批插槽结束,流水号："+nlsApplyInfoVO.getApplySeq());
        }
    }


    private boolean validateParam(NlsApplyInfoVO nlsApplyInfoVO,LmtPrdContVO lmtPrdContVO,CusIndivRelVO cusIndivRelVO,BigDecimal preOccAmt) throws BizException{
        if(Objects.isNull(cusIndivRelVO)){
            throw new BizException("联系人信息为空");
        }
        if(StringUtil.isNullorBank(nlsApplyInfoVO.getApplySeq())){
            throw new BizException("申请编号为空");
        }
        if(StringUtil.isNullorBank(nlsApplyInfoVO.getCusName())){
            throw new BizException("主卡申请人姓名为空");
        }
        if(StringUtil.isNullorBank(nlsApplyInfoVO.getCertCode())){
            throw new BizException("申请人证件号码为空");
        }
        if(StringUtil.isNullorBank(nlsApplyInfoVO.getCertType())){
            throw new BizException("申请人证件类型为空");
        }
        if(StringUtil.isNullorBank(nlsApplyInfoVO.getIndivIdExpDt())){
            throw new BizException("证件有效期为空");
        }
        if(StringUtil.isNullorBank(lmtPrdContVO.getExpireDate())){
            throw new BizException("额度有效期为空");
        }
        if (Objects.isNull(lmtPrdContVO.getAvailAmt())) {
            throw new BizException("可用额度为空");
        }
        if(StringUtil.isNullorBank(nlsApplyInfoVO.getMobile())){
            throw new BizException("联系电话为空");
        }
        if(Objects.isNull(nlsApplyInfoVO.getApplyAmt())){
            throw new BizException("申请金额为空");
        }
        if(StringUtil.isNullorBank(nlsApplyInfoVO.getLoanTerm())){
            throw new BizException("申请贷款期限为空");
        }
        if(StringUtil.isNullorBank(cusIndivRelVO.getMobile())){
            throw new BizException("联系人电话为空");
        }
        if(StringUtil.isNullorBank(cusIndivRelVO.getRelName())){
            throw new BizException("联系人姓名为空");
        }
        if(StringUtil.isNullorBank(cusIndivRelVO.getRelation())){
            throw new BizException("与联系人的关系类型为空");
        }
        if(Objects.isNull(preOccAmt)){
            throw new BizException("网络贷款占用额度为空");
        }
        return true;
    }

}
